<template>
  <VDialog
    @close="handleClose"
    @save="save"
    :loading="loading"
    width="600px"
    title="添加MAC地址"
  >
    <template #content>
      <div class="content">
        <template v-for="(refName, index) in 6" :key="index">
          <el-input
            v-model="value[index]"
            :maxlength="2"
            :id="`refName${index}`"
            clearable
            @input="(e) => handleInput(index, e)"
            @paste="pasting"
          />
          <span v-if="index < 5"></span>
        </template>
      </div>
    </template>
  </VDialog>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import { ElMessage } from "element-plus";
import api from "../../api/index";

const props = defineProps({
  ids: { type: Array, default: () => [] },
});
// 初始化输入框值
const value = ref(Array(6).fill(""));
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);

// 粘贴处理
const pasting = (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData("text");
  const arr = text.split("-").slice(0, 6);

  arr.forEach((res, index) => {
    value.value[index] = res;
  });

  nextTick(() => {
    console.log(arr.length);
    const nextInput = document.querySelector(`#refName${arr.length - 1}`);
    if (nextInput) {
      nextInput.focus();
    }
  });
};

// 处理输入并自动聚焦下一个输入框
const handleInput = (index, val) => {
  if (val.length === 2 && index <= 5) {
    console.log(3);
    nextTick(() => {
      document.querySelector(`#refName${index + 1}`).focus();
    });
  }
};

// 关闭对话框并触发相关事件
const handleClose = (refresh = false) => {
  value.value = Array(6).fill("");
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};

// 保存数据
const save = async () => {
  try {
    loading.value = true;
    const { code, message } = await api.setAddMac({
      id: props.ids.join(""),
      mac: value.value.join("-"),
    });
    if (code !== 200) return ElMessage.error(message);
    ElMessage.success("设置成功!");
    handleClose(true);
  } catch (error) {
    // 可以在这里处理错误
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.content {
  display: flex;
  align-items: center;
  margin: 20px;

  &:deep(.el-input__wrapper) {
    background-color: var(--base-small-bg-color);
    box-shadow: none;
  }

  span {
    width: 30px;
    height: 2px;
    background-color: #cfd1d7;
    margin: 0 10px;
    display: inline-block;
  }
}
</style>
